import $service from '../../service.js';
var that;
var Timer = null;
var t = 60;
let app = getApp();
let userList;
let sessionKey = '';
let doctorId = ''
let infoList = []
Page({
    data: {
        isShowPrivacy: false,
        privacyName: '',
        hisType: $service.isHis,
        loginType: 'P',
        loginTypeList: [{
            text: '用户',
            type: 'P',
        },{
            text: '医生',
            type: "D",
        }],
        isshow: false,
        password: '',
        phone: '',
        isFromMyDoctor: false,
        tabType: '',
        code: '',
        smsCode: '',
        list: [{
                value: 'P',
                name: '用户'
            },
            {
                value: 'D',
                name: '医生'
            },
            {
                value: 'S',
                name: '服务点'
            },
        ],
        items: [],
        isSend: false,
        countTime: 59,
        isTest: false,
        isCode: false,
        disabled: false,
        isagreen: false
    },
    onLoad(option) {
        if (option.isFromMyDoctor) {
            this.setData({
                isFromMyDoctor: true
            })
        } else {}
        doctorId = option.doctorId
    },
    onShow() {
        that = this.data;
        this.getSessionKey()
        // 打开隐私弹窗
        this.getPrivacySetting()
    },
    getPrivacySetting() {
      if ( wx.getPrivacySetting) {
        wx.getPrivacySetting({
          success: res => {
              if (res.needAuthorization) {
                  // 需要弹出隐私协议
                  this.setData({
                    isShowPrivacy: true,
                    privacyName: res.privacyContractName
                  })
              }
          },
          fail: err => {
              console.log(err)
          }
      })
      }
    },
    // 选择登陆方式
    checkType(e) {
        let {item} = e.currentTarget.dataset
        this.setData({
            "loginType": item.type,
        })
    },
    // 判断用户类型 
    judgeUser() {
        app.http.judgeUser({
            mobile: that.phone
        }).then(res => {
        }).catch(err => {
            if (err.data == null) {
                $service.showToast(err.msg);
            } else {
                $service.showToast(err.data[0]);
            }
        })
    },
    // login 
    async userLogin  () {
        this.setData({
            disabled: true
        })
        wx.login({
            success: (res) => {
                if (res.code) {
                    let params = {
                        "code": res.code,
                        "password": that.password,
                        "mobile": that.phone,
                        "smsCode": that.code,
                        "userType": that.loginType
                    }
                    app.http.userLogin(params).then(async res => {
                      let list = res.data.list;
                      let userInfo = list.find(item => item.type == that.loginType)
                      $service.setStore('userInfo', JSON.stringify(userInfo));
                      $service.setStore('miniToken', userInfo.miniToken);
                      if (userInfo.type === 'D') {
                          this.getDoctorInfo();
                          if ($service.isEsgin && !await this.checkCertification()) {
                            $service.openPage(`./caVerify/phoneAuth/phoneAuth?phone=${that.phone}`)
                            return
                          }
                          wx.reLaunch({
                            url: '../doctor_side/index/index'
                          })
                      } else {
                          if (doctorId) {
                              this.getUserInfo();
                              wx.reLaunch({
                                  url: '../user_side/index/index_doctorlist/index_doctor_details/index_doctor_details?doctorId=' + doctorId
                              })
                          } else {
                              this.getUserInfo();
                              if (this.data.isFromMyDoctor) {
                                  wx.reLaunch({
                                      url: '../user_side/my_doctor/index'
                                  })
                              } else {
                                  wx.reLaunch({
                                      url: '../user_index/user_index'
                                  })
                              }
                          }
                      }
                    }).catch(err => {
                        $service.showToast(err.msg);
                    }).finally(() => {
                        this.setData({
                            disabled: false
                        })
                    })
                } else {
                    this.setData({
                        disabled: false
                    })
                    $service.showToast('登录失败')
                }
            }
        })
    },
    // 缓存医生个人信息
    getDoctorInfo() {
        app.http.getDoctorInfo().then(res => {
            $service.setStore('doctorInfo', JSON.stringify(res.data));
        })
    },
    // 缓存用户个人信息
    getUserInfo() {
        app.http.getUserInfo().then(res => {
            $service.setStore('userData', JSON.stringify(res.data));
        })
    },
    // 登陆
    tohome() {
        if ($service.isUndefinedAndEmpty(that.phone)) {
            $service.showToast("请输入手机号");
            return;
        }
        if (!$service.validateElement('mobile', that.phone)) {
            $service.showToast('请输入正确的手机号！');
            return;
        }
        if ($service.isUndefinedAndEmpty(that.password)) {
            $service.showToast('请输入密码！');
            return;
        }
        if (that.password.trim().length < 6 || that.password.trim().length > 20) {
          $service.showToast('请输入6-20位密码！');
          return;
        }
        if ($service.isUndefinedAndEmpty(that.code)) {
            $service.showToast('请输入验证码！');
            return;
        }
        if (!this.data.isagreen) {
          $service.showToast('请查看并同意《服务协议与隐私政策》！');
          return;
        }
        this.userLogin();
    },

    // 发送短信
    sendCode() {
        if (!that.phone) {
          $service.showToast('请输入手机号码')
          return
        }
        let parmas = {
            "mobile": that.phone,
            "type": that.loginType == 'P' ? 1 : 3
        }
        app.http.phoneCaptcha(parmas).then(res => {
            $service.showToast(res.msg);
            this.setData({
                isSend: true,
            })
            this.count()
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 计时器
    count() {
        console.log('打开定时器')
        clearInterval(Timer)
        Timer = setInterval(() => {
            if (t == 1) {
                this.setData({
                    isSend: false
                })
                t = 60
                this.setData({
                    countTime: t
                })
                clearInterval(Timer)
                return
            }
            t--;
            this.setData({
                countTime: t
            })
        }, 1000);
    },
    inputChange(e) {
        var name = e.detail.value;
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            that.phone = name;
        } else if (index == 2) {
            that.password = name.replace(/[^\w\`\~\!\@\#\$\%\^\&\*\(\)\_\+\[\]\;\'\,\.\/\<\>\?\-\=\\]/ig, '');
        } else if (index == 3) {
            that.code = name
        }
        this.setData({
            phone: that.phone,
            password: that.password
        })
    },
    tapisshow(e) {
        this.data.isshow = !this.data.isshow;
        this.setData({
            isshow: this.data.isshow
        })
    },
    // 授权登陆
    getPhoneNumber(e) {
        let {
            encryptedData,
            errMsg,
            iv
        } = e.detail
        if (errMsg === "getPhoneNumber:ok") {
            wx.login({
                success: (res) => {
                    let params = {
                        "encryptedData": encryptedData,
                        "iv": iv,
                        "sessionKey": sessionKey,
                        "code": res.code
                    }
                    app.http.userAuthorization(params).then(res => {
                        $service.setStore('userInfo', JSON.stringify(res.data.list[0]));
                        $service.setStore('miniToken', res.data.list[0].miniToken);
                        this.getUserInfo();
                        console.log(this.data.isFromMyDoctor);
                        if (this.data.isFromMyDoctor) {
                            wx.reLaunch({
                                url: 'pages/user_side/my_doctor/index'
                            })
                        } else {
                            wx.reLaunch({
                                url: '/pages/user_index/user_index'
                            })
                        }
                    }).catch(err => {
                        $service.showToast(err.msg)
                    })
                }
            })
        }
    },
    getSessionKey() {
        wx.login({
            success: res => {
                console.log(res);
                if (res.code) {
                    app.http.getSessionKey({
                        code: res.code
                    }).then(res => {
                        sessionKey = res.data
                    })
                } else {
                    $service.showToast('操作失败')
                }
            }
        })
    },
    async checkCertification() {
      try {
        let res =  await app.http.checkCertification({mobile: this.data.phone})
        return res.data.isCertification == 1 ? true : false
      } catch (err) {
        $service.showToast(err.msg)
      }
    },

    // 勾选协议
    choosetap() {
      this.data.isagreen = !this.data.isagreen
      this.setData({
        isagreen: this.data.isagreen
      })
    },
    goToAgeen() {
      $service.openPage(`/pages/login/agreement/agreement?type=2`)
    }
})